from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from db import get_db
from api.routes.auth import get_current_user
from models.user import User
from models.translation_history import TranslationHistory
from schemas.translation import TranslationHistoryOut, TranslationHistoryCreate

router = APIRouter()


@router.get("/test")
def test_history_api(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    """测试API是否正常工作"""
    return {
        "message": "历史记录API正常工作",
        "user_id": current_user.id,
        "username": current_user.username,
        "database_connected": True
    }


@router.get("/", response_model=List[TranslationHistoryOut])
def list_my_translations(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    try:
        print(f"查询用户 {current_user.id} 的翻译历史")
        
        # 先检查用户是否存在
        if not current_user:
            print("用户不存在")
            return []
        
        # 查询翻译历史
        items = (
            db.query(TranslationHistory)
            .filter(TranslationHistory.user_id == current_user.id)
            .order_by(TranslationHistory.id.desc())
            .limit(100)
            .all()
        )
        
        print(f"找到 {len(items)} 条翻译记录")
        return items
        
    except Exception as e:
        print(f"查询翻译历史失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"查询翻译历史失败: {str(e)}"
        )


@router.post("/", response_model=TranslationHistoryOut)
def create_translation_history(data: TranslationHistoryCreate, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    item = TranslationHistory(
        user_id=current_user.id,
        source_text=data.source_text,
        translated_text=data.translated_text,
        source_lang=data.source_lang,
        target_lang=data.target_lang
    )
    db.add(item)
    db.commit()
    db.refresh(item)
    return item


@router.delete("/")
def clear_my_translations(current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
    """清空当前用户的所有翻译历史"""
    try:
        deleted_count = db.query(TranslationHistory).filter(
            TranslationHistory.user_id == current_user.id
        ).delete()
        db.commit()
        return {"message": f"已删除 {deleted_count} 条翻译记录"}
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"清空翻译历史失败: {str(e)}"
        )








